using UnityEngine;

public class Main : MonoBehaviour
{
    void Start()
    {
        // 初始化
        // sproto-Unity:
        NetCore.Init();
        NetSender.Init();
        NetReceiver.Init();
        NetCore.enabled = true;


        NetCore.Connect("127.0.0.1", 8888, () =>
        {
            Debug.Log("connect result: " + NetCore.connected);
            if (NetCore.connected)
            {
                // 给服务端发送一条set消息
                SendSet();
                // 给服务端发送一条get消息
                SendGet();

                SendCauchy();
            }
        });

        NetReceiver.AddHandler<Protocol.heartbeat>((data) =>
        {
            Debug.Log("收到服务端的heartbeat消息");
            return null;
        });
    }

    void Update()
    {
        // 驱动消息分发
        NetCore.Dispatch();
    }

    void SendGet()
    {
        var req = new SprotoType.get.request();
        req.what = "cauchy";
        Debug.Log("发送get消息给服务端");
        NetSender.Send<Protocol.get>(req, (data) =>
        {
            var rsp = data as SprotoType.get.response;
            Debug.LogFormat("服务端get返回, result: {0}", rsp.result);
        });
    }

    void SendSet()
    {
        var req = new SprotoType.set.request();
        req.what = "cauchy";
        req.value = "18";
        Debug.Log("发送set消息给服务端");
        NetSender.Send<Protocol.set>(req, (data) =>
        {
        });
    }

    void SendCauchy()
    {
        var req = new SprotoType.cauchy.request();
        req.what = "very headsome";
        Debug.Log("发送cauchy消息给服务端");
        NetSender.Send<Protocol.cauchy>(req, (data) =>
        {
            var rsp = data as SprotoType.cauchy.response;
            Debug.LogFormat("服务端cauchy返回, msg: {0}", rsp.msg);
        });
    }
}
